import JSZip from 'jszip'
import FileSaver from 'file-saver'
import axios from 'axios'
/**
 * 打包压缩下载
 * @param data  源文件数组
 * @param fileName  压缩文件的名称
 */
export const compressAndDownloadZip = (data = [], fileName = '') => {
  console.log(data, fileName)
  const zip = new JSZip()
  const promises = [] // 用于存储多个promise
  data.forEach((item) => {
    const promise = getFile(item.fileUrl).then((res) => {
      console.log(res)
      const fileName = item.fileName
      zip.file(fileName, res, { binary: true })
    })
    promises.push(promise)
  })

  Promise.all(promises).then(() => {
    console.log('>>>')
    zip
      .generateAsync({
        type: 'blob',
        compression: 'DEFLATE', // STORE：默认不压缩 DEFLATE：需要压缩
        compressionOptions: {
          level: 9 // 压缩等级1~9    1压缩速度最快，9最优压缩方式
        }
      })
      .then((res) => {
        FileSaver.saveAs(res, fileName || '压缩包.zip') // 利用file-saver保存文件
      })
  })
}

export const saveFile = (param = {}) => {
  const { content, url, name } = param
  if (url) {
    fetch(url)
      .then((response) => response.blob())
      .then((blob) => {
        FileSaver.saveAs(blob, name || `${uuid()}`)
      })
  } else {
    FileSaver.saveAs(content, name || `${uuid()}`)
  }
}

const getFile = (url = '', params = {}) => {
  return new Promise((resolve, reject) => {
    console.log('getFile', url)
    return axios({
      url,
      method: 'GET',
      params: params,
      responseType: 'blob' // 注意
      // headers: {
      //   'Content-Type': 'application/json; application/octet-stream'
      // }
    })
      .then((response) => {
        console.log(response)
        resolve(response.data)
      })
      .catch((err) => {
        reject(err)
      })
  })
}
const uuid = () => {
  var s = []
  var hexDigits = '0123456789abcdef'
  for (var i = 0; i < 32; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23]
  var uuid = s.join('')
  return uuid
}
